package pers.zh.parking.controller;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import pers.zh.parking.common.BaseController;
import pers.zh.parking.common.Const;
import pers.zh.parking.common.Response;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("file")
public class FileController extends BaseController {

    @RequestMapping("/upload")
    public Response upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        try {
            if (file.isEmpty()) {
                return Response.fail_401("文件为空");
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            fileName = String.valueOf(System.currentTimeMillis())+fileName.substring(fileName.lastIndexOf("."),fileName.length());
            logger.info("上传的文件名为：" + fileName);
            //设置文件存储路径
            String filePath = Const.UPLOAD_PATH;
            String path = filePath + fileName;
            String ServerUrl = request.getServerName()+":"+request.getServerPort()+"/download?fileName=";
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入

            return Response.ok("上传成功");
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Response.fail_500("上传失败");
    }

    @GetMapping("/download1")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "test.jpg";
        //获取文件的绝对路径
        String realPath = Const.DOWNLOAD_PATH;
        //获取输入流对象（用于读文件）
        FileInputStream fis = new FileInputStream(new File(realPath, fileName));
        //获取文件后缀（.txt）
        String extendFileName = fileName.substring(fileName.lastIndexOf('.'));
        //动态设置响应类型，根据前台传递文件类型设置响应类型
        response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName));
        //设置响应头,attachment表示以附件的形式下载，inline表示在线打开
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        //获取输出流对象（用于写文件）
        ServletOutputStream os = response.getOutputStream();
        //下载文件,使用spring框架中的FileCopyUtils工具
        FileCopyUtils.copy(fis,os);

    }

    @GetMapping("/download2")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = request.getParameter("fileName");// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File(Const.UPLOAD_PATH+fileName);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
}
